package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatRadioButton
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.ConfirmAnOrderResponse
import com.gexiaobao.pigeon.app.model.param.AddOrReGoodsParam
import com.gexiaobao.pigeon.app.model.param.CancelOrderParam
import com.gexiaobao.pigeon.app.model.param.ModifyReceiveAddressParam
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentOrderDetailBinding
import com.gexiaobao.pigeon.ui.adapter.ConfirmOrderAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/6/20 8:17
 * @Describe    : 确认订单
 */
class FragmentConfirmOrder : BaseFragment<MallViewModel, FragmentOrderDetailBinding>() {

    private var mBrandType: Int = 0
    private lateinit var dialog: RxDialogDefault
    private lateinit var dialogAddress: RxDialogDefault
    private val mAdapter: ConfirmOrderAdapter by lazy { ConfirmOrderAdapter(arrayListOf()) }
    private var id = ""
    private var totalPrice = ""
    private var orderStatus = 0
    private var isApply = false
    private var orderNewId = 0
    private lateinit var mOrderData: ConfirmAnOrderResponse
    private var useGebi: Int = 0
    private var mDeductionMoney = 0.0
    private var mFinalPrice = 0.0
    private var mDeduction = ""
    private var rbDeductionChecked = true
    private var rbDeductionUnChecked = true
    private var mIsRealName = true
    private var mHasIdCardPic = ""

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        id = arguments?.getString("orderId").toString()
        orderNewId = id.toInt()

        mDatabind.recyclerViewOrderDetail.init(LinearLayoutManager(context), mAdapter)
        mDatabind.recyclerViewOrderDetail.adapter = mAdapter

        eventViewModel.toNotifyChangeAddress.observeInFragment(this) { addressId ->
            showLoading(getString(R.string.loading))
            val body = ModifyReceiveAddressParam(orderId = orderNewId, addrId = addressId)
            mViewModel.changeAddress(body)
        }

        eventViewModel.toRefreshData.observeInFragment(this) {
            onRefresh()
        }

    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        onRefresh()
    }

    private fun onRefresh() {
        showLoading(getString(R.string.loading))
        mViewModel.getShopOrderList(id)
    }

    override fun onResume() {
        super.onResume()
        val addressData = CacheUtil.getAddressInfo()
        if (addressData != null) {
            mDatabind.addressData = addressData
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.ivBack,
            mDatabind.shopOrderDelete,
            mDatabind.llReceiveAddress,
            mDatabind.shopOrderPayment,
            mDatabind.shopOrderPayment1,
            mDatabind.llGeBiCount,
            mDatabind.includeRealName.llRealNameCard
        ) {
            when (it) {
                mDatabind.includeRealName.llRealNameCard -> {
                    if (!mIsRealName) {
                        nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
                            putString(Constant.INTO_TYPE, "mineBank")
                        })
                    }
                    if (mIsRealName && mHasIdCardPic.isEmpty()) {
                        nav().navigateAction(R.id.action_to_fragment_ocr)
                    }
                }

                mDatabind.ivBack -> {
                    eventViewModel.toRefreshData.value = true
                    nav().navigateUp()
                }

                mDatabind.shopOrderPayment, mDatabind.shopOrderPayment1 -> consumeMallApply()
                mDatabind.llReceiveAddress -> nav().navigateAction(R.id.action_to_receive_address, Bundle().apply {
                    putInt("type", 1)
                })

                mDatabind.shopOrderDelete -> shopOrderDelete()
                mDatabind.llGeBiCount -> showBottomDialogGeBi()
            }
        }
    }

    @SuppressLint("SetTextI18n", "MissingInflatedId")
    private fun showBottomDialogGeBi() {
        val dialog = context?.let { BottomSheetDialog(it) }
        val dialogView: View = LayoutInflater.from(context).inflate(R.layout.bottom_ge_bi, null)
        val rbDeduction = dialogView.findViewById<AppCompatRadioButton>(R.id.radioBtnDeduction)
        val rbNoDeduction = dialogView.findViewById<AppCompatRadioButton>(R.id.radioBtnNoDeduction)
        val tvUseDescribe = dialogView.findViewById<AppCompatTextView>(R.id.tvUseDescribe)
        val btnSubmit = dialogView.findViewById<AppCompatButton>(R.id.btnSubmit)
        val ivGeBiClose = dialogView.findViewById<AppCompatImageView>(R.id.ivGeBiClose)
        if (::mOrderData.isInitialized) {
            if (mOrderData.canCutMoney != 0.00) {
                mDeductionMoney = mOrderData.canCutMoney
                rbDeduction.text = "可使用" + mOrderData.gebiCnt + "鸽币抵现" + mDeductionMoney + "元"
            }
            tvUseDescribe.text = "最大可用" + mOrderData.gebiCnt + "鸽币,支付后将自动扣除。如遇退款等争议,可联系客服人员进行解决"
        }
        rbDeduction.isChecked = rbDeductionChecked
        rbNoDeduction.isChecked = rbDeductionUnChecked
        rbDeduction.setOnCheckedChangeListener { _, isChecked ->
            rbDeductionChecked = isChecked
        }
        rbNoDeduction.setOnCheckedChangeListener { _, isChecked ->
            rbDeductionUnChecked = isChecked
        }
        ivGeBiClose.setOnClickListener {
            dialog?.dismiss()
        }
        btnSubmit.setOnClickListener {
            if (rbDeductionChecked) {
                mDatabind.tvGebiCanUse.text = getString(R.string.rmb) + mDeductionMoney.toString()
            } else {
                mDatabind.tvGebiCanUse.text = "可用"
            }
//            mDatabind.tvGeBiDeduction.text = mDeductionMoney.toString()
            mDeduction = Util.sub(totalPrice, mDeductionMoney.toString())
            useGebi = if (rbDeductionChecked) {
                1
            } else {
                0
            }
            if (useGebi == 1) {
                mDatabind.tvTopPayMoney.text = "需付款: $mDeduction"
                SettingUtil.setPrice(
                    mDeduction, mDatabind.tvOrderDetailFinalPrice, 60,
                    ContextCompat.getColor(requireContext(), R.color.color_fe4542)
                )
            } else {
                mDatabind.tvTopPayMoney.text = "需付款: $totalPrice"
                SettingUtil.setPrice(
                    totalPrice, mDatabind.tvOrderDetailFinalPrice, 60,
                    ContextCompat.getColor(requireContext(), R.color.color_fe4542)
                )
            }
            dialog?.dismiss()
        }
        dialog!!.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.setContentView(dialogView)
        dialog.show()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 更改收货地址 */
        mViewModel.changeAddressResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it != null) {
                orderNewId = it.orderId
                showLoading(getString(R.string.loading))
                mViewModel.getShopOrderList(orderNewId.toString())
            }
        }
        /** 取消订单 */
        mViewModel.cancelOrderResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                dialog.dismiss()
                nav().navigateUp()
                eventViewModel.toRefreshListShopOrder.value = true
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 删除订单 */
        mViewModel.deleteOrderResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                dialog.dismiss()
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取订单详情  */
        mViewModel.orderDetailResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it != null) {
                refreshUIData(it)
            }
        }
    }

    private fun showSettingAddressDialog() {
        dialogAddress = RxDialogDefault(context)
        dialogAddress.setTitle("你还没有收货地址，赶紧去设置一个吧")
        dialogAddress.setRightBtnContent("去设置")
        dialogAddress.setSureListener {
            dialogAddress.dismiss()
            nav().navigateAction(R.id.action_to_add_receive_address, Bundle().apply {
                putString("type", "")
            })
        }
        dialogAddress.setCancelListener {
            dialogAddress.dismiss()
            nav().navigateUp()
        }
        dialogAddress.setFullScreenWidth()
        dialogAddress.show()
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    private fun refreshUIData(it: ConfirmAnOrderResponse) {
        mOrderData = it
        orderStatus = it.orderStatus
        if (orderStatus == 9) {
            mDatabind.tvOrderState.setTextColor(Color.BLACK)
            mDatabind.ivOrderState.setImageResource(R.mipmap.icon_cancel_order_status)
        } else {
            mDatabind.ivOrderState.setImageResource(R.mipmap.icon_wait_pay_white)
            mDatabind.tvOrderState.setTextColor(Color.WHITE)
        }
        mBrandType = it.brandType
        mDatabind.includeRealName.llRealNameCard.isVisible = mBrandType == 2
        mHasIdCardPic = it.hasIdCardPic
        mIsRealName = it.isRealName
        if (mBrandType == 2) {
            if (mHasIdCardPic.isNotEmpty()) {
                mDatabind.includeRealName.tvOrderInfoIdCard.text = it.idCardName + ", " + it.idCardNo
                mDatabind.includeRealName.tvOrderInfoIdCard.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                mDatabind.includeRealName.tvOrderInfoIdCardHint.text = "请确保实名信息与付款账号一致"
                mDatabind.includeRealName.tvOrderGoRealName.text = "修改"
            } else {
                mDatabind.includeRealName.tvOrderInfoIdCard.text = "此商品需进行清关操作"
                mDatabind.includeRealName.tvOrderInfoIdCard.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_light))
                mDatabind.includeRealName.tvOrderInfoIdCardHint.text = "请上传身份证照片进行实名"
                mDatabind.includeRealName.tvOrderGoRealName.text = "去实名"
            }
        }
        isApply = it.isApply
//        var totalExpressFree = BigDecimal("0.00")
//        if (!it.isEmpty()) {
//            it.list.forEachIndexed { _, storeInfoList ->
//                val expressFree = BigDecimal(storeInfoList.shopExpressFee.toString())
//                totalExpressFree = totalExpressFree.add(expressFree)
//            }
//        }
        mDatabind.tvExpressFee.text = context?.resources!!.getString(R.string.rmb) + it.totalExpressFee.toString().trim()
        mFinalPrice = it.finalPrice
        totalPrice = it.finalPrice.toString()
        context?.resources?.let { it1 ->
            SettingUtil.setPrice(
                totalPrice,
                mDatabind.tvOrderDetailFinalPrice,
                60,
                it1.getColor(R.color.color_red)
            )
        }
        mDatabind.tvTopPayMoney.text = "需付款: $totalPrice"
        mDatabind.data = it
        computingTime(it)
        if (!it.isEmpty()) {
            mAdapter.setList(it.list)
            mAdapter.notifyDataSetChanged()
        }
        if (it.canCutMoney == 0.00) {
            mDatabind.llGeBiCount.isClickable = false
            mDatabind.tvGebiCanUse.text = "不可用"
            mDatabind.tvGebiCanUse.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_light))
            mDatabind.ivGebiCanUse.setImageResource(R.mipmap.arrow_right)
        } else {
            mDatabind.llGeBiCount.isClickable = true
            mDatabind.tvGebiCanUse.text = "可用"
            mDatabind.tvGebiCanUse.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
            mDatabind.ivGebiCanUse.setImageResource(R.mipmap.icon_arrow_right_red)
        }
    }

    private fun consumeMallApply() {
        val address = mDatabind.tvReceiveAddress.text.toString().trim()
        val name = mDatabind.tvReceiveName.text.toString().trim()
        val phone = mDatabind.tvReceivePhone.text.toString().trim()
        if (address.isEmpty() || name.isEmpty() || phone.isEmpty()) {
            RxToast.showToast("请先添加收货地址")
            return
        }
        if (mBrandType == 2 && mHasIdCardPic.isEmpty()) {
            showMessage("此商品需进行清关操作，请上传身份证照片")
            return
        }
        val intentType = requireArguments().getString("type").toString()
        nav().navigateAction(R.id.action_to_shop_cashier, Bundle().apply {
            putString("price", if (useGebi == 0) totalPrice else mDeduction)
            putString("orderReceiver", name)
            putString("orderAddress", address)
            putString("orderContactPhone", phone)
            putString("intentType", intentType)
            putInt("orderId", if (orderNewId == 0) id.toInt() else orderNewId)
            putInt("useGebi", useGebi)
            putBoolean("isApply", isApply)
        })
    }

    private fun shopOrderDelete() {
        val dialogTitle = if (orderStatus == 9) {
            "是否删除该订单?"
        } else {
            "是否取消该订单?"
        }
        dialog = RxDialogDefault(context)
        dialog.setTitle(dialogTitle)
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            if (orderStatus == 9) {
                val body = AddOrReGoodsParam(id = id.toInt())
                mViewModel.userDeleteOrder(body)
            } else {
                val body = CancelOrderParam(orderId = id.toInt())
                mViewModel.cancelOrder(body)
            }
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    @SuppressLint("SetTextI18n")
    private fun computingTime(it: ConfirmAnOrderResponse) {
        val createTime = it.createdAt//创建时间
        val expireTime = it.expireTime//到期时间

        /** 到期时间-创建时间 = 剩余计时时间 */
//        val countTime = DatetimeUtil.getTimeDifferenceMinute(expireTime, createTime)
//        timeCount = TimeCount(countTime * 60 * 1000, 1000)
        timeCount = TimeCount(it.closeSecond * 1000, 1000)
        timeCount.start()
    }

    private var timeCount = TimeCount(60000, 1000)

    inner class TimeCount(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {

        @SuppressLint("SetTextI18n")
        override fun onTick(millisUntilFinished: Long) {
            mDatabind.shopOrderTimeout.text =
                getString(R.string.remain) + DatetimeUtil.formatDateTime(millisUntilFinished / 1000) + getString(R.string.market_shop_order_sure_activity_automatic_closing)
        }

        override fun onFinish() {
            nav().navigateUp()
            eventViewModel.toRefreshListShopOrder.value = true
        }
    }

    override fun onPause() {
        super.onPause()
        timeCount.cancel()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        timeCount.cancel()
    }
}